package com.lry.app;

import com.lry.app.service.KvService;
import com.lry.client.RpcClient;
import com.lry.client.RpcProxy;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

public class ClientMain {

    private AtomicInteger atomicLong = new AtomicInteger(0);
    List<RpcClient> rpcClientList = new ArrayList<>();

    public static void main(String[] args) {
        ClientMain clientMain = new ClientMain();
        clientMain.initRpcClient();

        System.out.println(clientMain.set("key", "value"));

        System.out.println(clientMain.getAll("key"));
    }

    public void initRpcClient(){
        RpcClient rpcClient1 = new RpcClient("localhost",8081);
        RpcClient rpcClient2 = new RpcClient("localhost",8082);
//        RpcClient rpcClient3 = new RpcClient("localhost",8083);
        rpcClientList.add(rpcClient1);
        rpcClientList.add(rpcClient2);
//        rpcClientList.add(rpcClient3);
    }

    public boolean set(String key,String value){
        KvService kvService = getKvService();
        return kvService.set(key,value);
    }

    public List<String> getAll(String key){
        List<String> list = new ArrayList<>();
        for (RpcClient rpcClient : rpcClientList) {
            KvService kvService = RpcProxy.getProxy(rpcClient, KvService.class);
            String value = kvService.get(key);
            list.add(value);
        }
        return list;
    }
    public String get(String key){
        KvService kvService = getKvService();
        return kvService.get(key);
    }

    public KvService getKvService(){
        int index = (atomicLong.getAndIncrement()%rpcClientList.size());
        return RpcProxy.getProxy(rpcClientList.get(index), KvService.class);
    }
}
